package com.mxx.common.payment;

import com.mxx.common.exception.UnsupportedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/8/14 16:52
 * @Description: 暂无描述
 */
@Slf4j
public class ApplicationTradeContext implements ApplicationContextAware {

    private Map<TradeType, PaymentHandler> paymentHandlerMap = new HashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, PaymentHandler> paymentHandlerMap = applicationContext.getBeansOfType(PaymentHandler.class);
        for (Map.Entry<String, PaymentHandler> entry : paymentHandlerMap.entrySet()) {
            PaymentHandler paymentHandler = entry.getValue();
            TradeType tradeType = paymentHandler.getTradeType();
            if (this.paymentHandlerMap.containsKey(tradeType)) {
                throw new UnsupportedException("unsupported operator , duplicate trade type [{}]", tradeType);
            }
            log.info(">>>>>> load paymentHandler [{} >>> {}]", tradeType, paymentHandler.getClass());
            this.paymentHandlerMap.put(tradeType, paymentHandler);
        }
        log.info(">>>>>> load paymentHandler complete . number [{}]", paymentHandlerMap.size());
    }

    public PrepaymentResponse prepayment(TradeType tradeType, TradeMark tradeMark) {
        return getHandler(tradeType).prepaymentProcess(tradeMark);
    }


    public PaymentHandler getHandler(TradeType tradeType) {
        PaymentHandler paymentHandler = paymentHandlerMap.get(tradeType);
        if (paymentHandler == null) {
            throw new UnsupportedException("unsupported tradeType [%s] ,Please check the loading status of related components", tradeType.name());
        }
        return paymentHandler;
    }
}
